from toolsSrc.files.checkFiles import checkCsvFiles
from common.config import pitchConfig as Config
import pandas as pd
import numpy as np
from toolsSrc.dbtools.getDBData import getWindSpeedFromDBData1


''' CALL BACK   改用下面的函数，这个现在不用了 #######################################################
1. 从Config.data1File文件 中读取当前风速
2. 在 Config.onlLineRegress文件 中查找风速最接近的 pitchAngle
3. 将 {‘PitchOffset’:[pitchAngle]} 写入Config.pitchUpload文件
'''
def toPitchUploadCsv_byData1File():
    if checkCsvFiles([Config.data1File, Config.onlLineRegress]) is False:
        return

    df_data1File = pd.read_csv(Config.data1File)
    df_onlLineRegress = pd.read_csv(Config.onlLineRegress)
    windSpeed = df_data1File.loc[0, Config.WindSpeed]

    WindSpeed_new = np.array(abs(df_onlLineRegress[Config.WindSpeed] - windSpeed))
    min = np.min(WindSpeed_new)
    indexMin = np.argmin(WindSpeed_new)
    if min > 1: return  # 如果最小偏差都很大，不进行后面的上传操作
    df_pitchUpload = pd.DataFrame({Config.pitchPlcKey: [df_onlLineRegress.loc[indexMin, Config.PitchAngle]]})
    print("当前风速：", windSpeed, Config.pitchPlcKey, "：", df_pitchUpload.iloc[0, 0])
    df_pitchUpload.to_csv(Config.pitchUpload, index=False)



''' CALL BACK #################################################################################
1. 从数据库data1表中读取当前风速
2. 在 Config.onlLineRegress文件 中查找风速最接近的 pitchAngle
3. 将 {‘PitchOffset’:[pitchAngle]} 写入Config.pitchUpload文件
'''
def toPitchUploadCsv():
    if checkCsvFiles([Config.onlLineRegress]) is False:
        return

    windSpeed = getWindSpeedFromDBData1()
    df_onlLineRegress = pd.read_csv(Config.onlLineRegress)
    
    WindSpeed_new = np.array(abs(df_onlLineRegress[Config.WindSpeed] - windSpeed))
    min = np.min(WindSpeed_new)
    indexMin = np.argmin(WindSpeed_new)
    if min > 1: return  # 如果最小偏差都很大，不进行后面的上传操作
    df_pitchUpload = pd.DataFrame({Config.pitchPlcKey: [df_onlLineRegress.loc[indexMin, Config.PitchAngle]]})
    print("当前风速：", windSpeed, Config.pitchPlcKey, "：", df_pitchUpload.iloc[0, 0])
    df_pitchUpload.to_csv(Config.pitchUpload, index=False)